// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
// 获取数据库对象及数据库
const db = uniCloud.database()
const dbCmd = db.command
const billsCollection = db.collection('bills-list')
const labelsCollection = db.collection('labels-list')

const getBill = async option => {
	let params = {}
	if (option.dateRange) {
		let [gte, lte] = option.dateRange
		params.date = dbCmd.lte(lte).gte(gte)
	}
	option.owner && (params.owner = option.owner)
	option.label && (params.labels = dbCmd.elemMatch(dbCmd.eq(option.label)))
	return await billsCollection.where(params).get()
}

const getLabels = async (owner) => {
	const res = await labelsCollection.where({
		owner
	}).get()
	return res?.data
}

const splitLabels = async (owner, labels) => {
	const bdLabels = await getLabels(owner);
	const inDbLabels = []
	const notInDbLabels = []
	labels.forEach(label => {
		if (!bdLabels.find(_label => _label.value == label)) {
			notInDbLabels.push(label)
		} else {
			inDbLabels.push(label)
		}
	})
	return {
		inDbLabels,
		notInDbLabels
	}
}

const handleLabels = async (owner, labels) => {
	const {
		inDbLabels,
		notInDbLabels
	} = await splitLabels(owner, labels)
	if (notInDbLabels.length) {
		await labelsCollection.add(notInDbLabels.map(value => {
			return {
				value,
				owner,
				count: 1
			}
		}))
	}
	if (inDbLabels.length) {
		for (let i = 0; i < inDbLabels.length; i++) {
			const value = inDbLabels[i]
			await labelsCollection.where({
				value,
				owner
			}).update({
				count: dbCmd.inc(1)
			})
		}
	}
}

const addBill = async option => {
	const {
		owner,
		labels
	} = option
	await handleLabels(owner, labels)
	const addBillRes = await billsCollection.add(option)
	return addBillRes
}

module.exports = {
	getBill,
	addBill,
	getLabels,
}